<?php
// +----------------------------------------------------------------------
// | Bwsaas
// +----------------------------------------------------------------------
// | Copyright (c) 2015~2020 http://www.buwangyun.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Gitee ( https://gitee.com/buwangyun/bwsaas )
// +----------------------------------------------------------------------
// | Author: buwangyun <hnlg666@163.com>
// +----------------------------------------------------------------------
// | Date: 2020-9-28 10:55:00
// +----------------------------------------------------------------------

namespace app\manage\controller\member;

use buwang\base\MemberBaseController;
use app\common\model\SysUploadfile;
use upload\Uploadfile;
use think\db\Query;
use buwang\base\AdminBaseController;
use buwang\service\UploadService;

class PublicCommon extends MemberBaseController
{
    /*protected $middleware = [
        'login' => ['except' => ['icon', 'upload', 'getlist', 'edit', 'uploadimg']]
    ];*/

    //图标库页面
    public function icon()
    {
        //View::assign('url', 'index页面');
        return view('public/icon');
    }

    public function index()
    {
        //取组合数据实例
        $data = new  \app\manage\model\ConfigGroupData;
        $list = $data->where('group_id', 73)->select()->toArray();;
        $data = bw_value_data($list);
        if (!$data) return $this->error(bw_value_data_errormsg());


        return $this->success('上传成功', $list);
    }

    /**
     * 上传文件
     * @param string $filename input框的name
     * @param string $filepath 存储路径
     * @param string $rule 验证规则
     * @param int $maxsize 允许文件上传的大小 默认为2m
     * @param bool $fileas 是否用原文件名上传保存 默认false
     * @return array
     */
    public function uploadimg($filename = 'file', $filepath = '', $rule = 'fileExt:jpg,jpeg,png,gif,pem|fileMime:image/jpeg,image/gif,image/png,text/plain', $fileas = false)
    {

        $file = request()->file($filename);

        try {
            $info = UploadService::uploadFile($file, $filename, $filepath, $rule, $fileas);
            return self::rMsg(0, '上传成功', $info['src'], $info['original_name']);
        } catch (\Exception $e) {
            return self::rMsg(1, $e->getMessage());
        }
    }

    /**  layui上传返回格式
     * @param $code
     * @param $msg
     * @param null $src
     * @param null $file_name
     * @return string
     */
    private static function rMsg($code, $msg, $src = null, $file_name = null)
    {
        $array = array();
        $array['msg'] = $msg;
        $array['code'] = $code;
        $array['data'] = null;
        if ($src) $array['data']['src'] = $src;
        if ($file_name) $array['data']['title'] = $file_name;
        return json($array);//数组转json
    }

//    public function upload($filename = 'file', $filepath = '', $rule = 'fileExt:jpg,jpeg,png,gif,pem|fileMime:image/jpeg,image/gif,image/png,text/plain', $fileas = false)
//    {
//        $file = request()->file($filename);
//
//        //var_dump($disk);die;
//        try {
//           $info = UploadService::uploadFile($file, $filename, $filepath, $rule, $fileas);
//        } catch (\Exception $e) {
//            return $this->error($e->getMessage(), ['errorMsg' => $e->getMessage()]);
//        }
//        return $this->success('上传成功', ['src' => $info['src']]);
//    }
    /**
     * 上传文件
     */
    public function upload()
    {
        $data = [
            'upload_type' => $this->request->post('upload_type'),
            'file' => $this->request->file('file'),
        ];
        $uploadConfig = bw_config('base');
        $uploadConfig['upload_allow_type'] = "local,alioss,qnoss,txcos";
        empty($data['upload_type']) && $data['upload_type'] = $uploadConfig['upload_type'];
        if ($data['upload_type'] !== 'local') {
            $uploadConfig = array_merge($uploadConfig, bw_config($data['upload_type']));
        }
        $rule = [
            'upload_type|指定上传类型有误' => "in:{$uploadConfig['upload_allow_type']}",
            'file|文件' => "require|file|fileExt:{$uploadConfig['upload_allow_ext']}|fileSize:{$uploadConfig['upload_allow_size']}",
        ];
        $this->validate($data, $rule);
        try {
            $upload = Uploadfile::instance()
                ->setUploadType($data['upload_type'])
                ->setUploadConfig($uploadConfig)
                ->setFile($data['file'])
                ->save();
        } catch (\Exception $e) {
            return $this->error($e->getMessage());
        }
        if ($upload['save'] == true) {
            return $this->success($upload['msg'], ['src' => $upload['url']]);
        } else {
            return $this->error($upload['msg']);
        }
    }

    /**
     * 上传图片至编辑器
     * @return \think\response\Json
     */
    public function uploadEditor()
    {
        $data = [
            'upload_type' => $this->request->post('upload_type'),
            'file' => $this->request->file('upload'),
        ];
        $uploadConfig = bw_config('base');
        $uploadConfig['upload_allow_type'] = "local,alioss,qnoss,txcos";
        empty($data['upload_type']) && $data['upload_type'] = $uploadConfig['upload_type'];
        if ($data['upload_type'] !== 'local') {
            $uploadConfig = array_merge($uploadConfig, bw_config($data['upload_type']));
        }
        $rule = [
            'upload_type|指定上传类型有误' => "in:{$uploadConfig['upload_allow_type']}",
            'file|文件' => "require|file|fileExt:{$uploadConfig['upload_allow_ext']}|fileSize:{$uploadConfig['upload_allow_size']}",
        ];
        $this->validate($data, $rule);
        try {
            $upload = Uploadfile::instance()
                ->setUploadType($data['upload_type'])
                ->setUploadConfig($uploadConfig)
                ->setFile($data['file'])
                ->save();
        } catch (\Exception $e) {
            return $this->error($e->getMessage());
        }
        if ($upload['save'] == true) {
            return json([
                'error' => [
                    'message' => '上传成功',
                    'number' => 201,
                ],
                'fileName' => '',
                'uploaded' => 1,
                'url' => $upload['url'],
            ]);
        } else {
            return $this->error($upload['msg']);
        }
    }

    /**
     * 获取上传文件列表
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getUploadFiles()
    {
        $get = $this->request->get();
        $page = isset($get['page']) && !empty($get['page']) ? $get['page'] : 1;
        $limit = isset($get['limit']) && !empty($get['limit']) ? $get['limit'] : 10;
        $title = isset($get['title']) && !empty($get['title']) ? $get['title'] : null;
        $this->model = new SysUploadfile();
        $count = $this->model
            ->where(function (Query $query) use ($title) {
                !empty($title) && $query->where('original_name', 'like', "%{$title}%");
            })
            ->count();
        $list = $this->model
            ->where(function (Query $query) use ($title) {
                !empty($title) && $query->where('original_name', 'like', "%{$title}%");
            })
            ->page($page, $limit)
            ->order($this->sort)
            ->select();
        $data = [
            'code' => 0,
            'msg' => '',
            'count' => $count,
            'data' => $list,
        ];
        return json($data);
    }

}